#include "voiceSu03t.h"
#include "stdio.h"

void IRAM_ATTR voiceSerialReceive();

VOICESU03T::VOICESU03T(int8_t uart_num, int8_t tx_pin, int8_t rx_pin, uint32_t baud_rate) {
    _uart_num = uart_num;
    _tx_pin = tx_pin;
    _rx_pin = rx_pin;
    _baud_rate = baud_rate;
    switch (_uart_num) {
        case 1:
            serial = &Serial1;
            break;
        case 2:
            serial = &Serial2;
            break;
        // 可以根据需要添加更多串口
    }
}

void VOICESU03T::begin() {
    if (serial) {
        serial->begin(_baud_rate, SERIAL_8N1, _rx_pin, _tx_pin);

        // 注册中断服务例程
        serial->onReceive(voiceSerialReceive);
       
    }
}

size_t VOICESU03T::write(uint8_t *data, size_t size) {
    if (serial) {
        return serial->write((const uint8_t *)data, size);
    }
    return 0;
}

int VOICESU03T::read() {
    if (serial) {
        return serial->read();
    }
    return -1;
}

int VOICESU03T::available() {
    if (serial) { 
        return serial->available();
    }
    return 0;
}

void VOICESU03T::setState(int8_t state)
{
   _state = state;
}

int8_t VOICESU03T::getState()
{
    return _state;
}

//将10进制转换为16进制的HEX
//参数：decimal（传入的10进制数）
//返回：16进制hex
long VOICESU03T::decimalToHex_big(long decimal)
{
	long hex = 0;
	int i = 0;
	char temp_buff[20];
	
	sprintf(temp_buff, "%lX", decimal);//换为字符串的16进制
	//根据字符串长度一直转换
  	for( i  =0 ; temp_buff[i] != '\0'; i++ )
	{
		//如果是数字
		if( temp_buff[i] >= '0' && temp_buff[i] <= '9' )
		{
			hex = (hex << 4) | temp_buff[i]-'0';
		}
		else//如果是字母
		{
			switch( temp_buff[i] )
			{   //先左移再转换
				case 'A':	hex = (hex << 4) | 0x0A;	break;
				case 'B':	hex = (hex << 4) | 0x0B;	break;
				case 'C':	hex = (hex << 4) | 0x0C;	break;
				case 'D':	hex = (hex << 4) | 0x0D;	break;
				case 'E':	hex = (hex << 4) | 0x0E;	break;
				case 'F':	hex = (hex << 4) | 0x0F;	break;
			}
		}
	}
	return hex;
}

void VOICESU03T::voiceSpeechTime(long hour, long min)
{
    unsigned char sendBuff[7] = { 0xAA, 0X55, 0X01, 0X00, 0X00, 0X55, 0xAA };

    sendBuff[3] = decimalToHex_big(hour);
    sendBuff[4] = decimalToHex_big(min);
    write(sendBuff, 7);
}

void VOICESU03T::voiceSpeechHumiture(long temp, long humi)
{
    unsigned char sendBuff[7] = { 0xAA, 0X55, 0X02,0X00, 0X00, 0X55, 0xAA };

    sendBuff[3] = decimalToHex_big(temp);
    sendBuff[4] = decimalToHex_big(humi);
    write(sendBuff, 7);
}